package com.example.webcrawler.service.mpl;

import com.example.webcrawler.model.ApiRequest;
import com.example.webcrawler.model.DebugSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;

import java.net.http.HttpClient;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;


@Service
public class WebAnalysisService {
    private static final Logger logger = LoggerFactory.getLogger(WebAnalysisService.class);
    private final HttpClient httpClient = HttpClient.newHttpClient();

    // 添加Page对象管理
    private final Map<String, Page> pageMap = new ConcurrentHashMap<>();
    private final Map<String, String> pageIdMap = new ConcurrentHashMap<>();

    // 添加CA证书和私钥存储
    private X509Certificate caCert;
    private PrivateKey caPrivateKey;

    @Autowired
    private HttpsProxyService httpsProxyService;

    @Autowired
    private DebugService debugService;


    private java.util.function.Consumer<ApiRequest> requestBroadcaster;
    private java.util.function.Function<String, Boolean> interceptChecker;

    // 添加设置广播器的方法
    public void setRequestBroadcaster(java.util.function.Consumer<ApiRequest> broadcaster) {
        this.requestBroadcaster = broadcaster;
    }

    // 添加设置拦截检查器的方法
    public void setInterceptChecker(java.util.function.Function<String, Boolean> checker) {
        this.interceptChecker = checker;
    }

    /**
     * 启动带调试功能的页面分析
     */
    public List<ApiRequest> analyzeWithDebug(String url, boolean headless) {
        List<ApiRequest> requests = new CopyOnWriteArrayList<>();
        Playwright playwright = null;
        Browser browser = null;
        BrowserContext context = null;
        Page page = null;
        String debugSessionId = null;
        String pageId = null;

        try {
            // 创建Playwright实例
            playwright = Playwright.create();

            // 配置浏览器启动选项
            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions()
                    .setHeadless(headless);

            // 启动浏览器
            browser = playwright.chromium().launch(launchOptions);

            // 创建浏览器上下文
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions();
            context = browser.newContext(contextOptions);

            // 创建页面
            page = context.newPage();

            // 注册页面ID
            pageId = "page-" + UUID.randomUUID().toString();
            pageMap.put(pageId, page);
            pageIdMap.put(pageId, url);

            // 创建调试会话
            debugSessionId = debugService.createDebugSession(page);
            if (debugSessionId == null) {
                logger.warn("Failed to create debug session, continuing without debugging");
            } else {
                logger.info("Debug session created: {}", debugSessionId);
            }

            // 设置请求拦截
            setupRequestInterception(context, requests);

            // 导航到目标URL
            logger.info("Navigating to URL: {}", url);
            page.navigate(url);

            // 等待页面加载完成
            page.waitForLoadState(LoadState.NETWORKIDLE);
            logger.info("Page loaded successfully");

            // 在实际应用中，这里会与前端交互进行调试
            // 比如设置断点、单步执行等
            // 等待调试完成的信号（在实际实现中可能需要更复杂的同步机制）
            waitForDebuggingCompletion(debugSessionId);

        } catch (Exception e) {
            logger.error("带调试功能的页面分析出错: {}", e.getMessage(), e);
        } finally {
            // 清理资源
            if (debugSessionId != null) {
                debugService.detachSession(debugSessionId);
            }

            // 注销页面ID
            if (pageId != null) {
                pageMap.remove(pageId);
                pageIdMap.remove(pageId);
            }

            if (page != null) {
                page.close();
            }
            if (context != null) {
                context.close();
            }
            if (browser != null) {
                browser.close();
            }
            if (playwright != null) {
                playwright.close();
            }
        }

        return requests;
    }

    /**
     * 根据页面ID获取Page对象
     */
    public Page getPageById(String pageId) {
        return pageMap.get(pageId);
    }

    /**
     * 获取所有页面ID列表
     */
    public Set<String> getAllPageIds() {
        return pageMap.keySet();
    }

    /**
     * 根据页面ID获取页面URL
     */
    public String getUrlByPageId(String pageId) {
        return pageIdMap.get(pageId);
    }

    /**
     * 等待调试完成
     * 在实际实现中，这可能需要与前端进行WebSocket通信
     */
    private void waitForDebuggingCompletion(String debugSessionId) {
        // 简化实现：等待一段时间或直到调试会话结束
        if (debugSessionId != null) {
            DebugSession session = debugService.getDebugSession(debugSessionId);
            long startTime = System.currentTimeMillis();
            long timeout = 30000; // 30秒超时

            while (session != null && session.isPaused() && (System.currentTimeMillis() - startTime) < timeout) {
                try {
                    Thread.sleep(100); // 短暂休眠避免忙等待
                    session = debugService.getDebugSession(debugSessionId);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }


    public List<ApiRequest> analyzeWebsite(String url, String username, String password) {
        logger.info("开始分析网站: {}", url);
        List<ApiRequest> allRequests = new ArrayList<>();

        // 生成流程ID
        String flowId = UUID.randomUUID().toString();
        logger.info("为本次分析生成流程ID: {}", flowId);

        // 静态分析
        logger.debug("执行静态分析");
        List<ApiRequest> staticRequests = performStaticAnalysis(url);
        if (staticRequests != null) {
            // 为静态请求设置流程ID
            staticRequests.forEach(req -> {
                req.setFlowId(flowId);
                req.setTimestamp(System.currentTimeMillis());
            });
            allRequests.addAll(staticRequests);
            logger.debug("静态分析完成，发现 {} 个请求", staticRequests.size());
        }

        // 动态分析
        logger.debug("执行动态分析");
        List<ApiRequest> dynamicRequests = performDynamicAnalysis(url, username, password);
        if (dynamicRequests != null) {
            // 为动态请求设置流程ID
            dynamicRequests.forEach(req -> {
                req.setFlowId(flowId);
                req.setTimestamp(System.currentTimeMillis());
            });
            allRequests.addAll(dynamicRequests);
            logger.debug("动态分析完成，发现 {} 个请求", dynamicRequests.size());
        }

        // 对请求进行去重
        List<ApiRequest> uniqueRequests = deduplicateRequests(allRequests);
        logger.info("网站分析完成，总共发现 {} 个API请求（去重后），流程ID: {}", uniqueRequests.size(), flowId);

        return uniqueRequests;
    }


    /**
     * 对请求进行去重处理
     */
    private List<ApiRequest> deduplicateRequests(List<ApiRequest> requests) {
        Map<String, ApiRequest> uniqueRequests = new LinkedHashMap<>();

        for (ApiRequest request : requests) {
            // 使用URL+Method作为唯一键
            String key = request.getMethod() + ":" + request.getUrl();

            // 如果已存在该请求，保留信息更完整的那个
            if (uniqueRequests.containsKey(key)) {
                ApiRequest existing = uniqueRequests.get(key);

                // 如果新请求有状态码而现有请求没有，则替换
                if (request.getStatus() != null && existing.getStatus() == null) {
                    uniqueRequests.put(key, request);
                }
                // 如果新请求是动态分析的而现有请求是静态分析的，则替换
                else if ("Dynamic".equals(request.getSource()) && !("Dynamic".equals(existing.getSource()))) {
                    uniqueRequests.put(key, request);
                }
            } else {
                uniqueRequests.put(key, request);
            }
        }

        return new ArrayList<>(uniqueRequests.values());
    }

    private List<ApiRequest> performStaticAnalysis(String url) {
        logger.info("开始对 {} 进行静态分析", url);
        List<ApiRequest> requests = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    .timeout(10000)
                    .get();

            // 查找所有可能的API端点
            findApiEndpointsInElements(doc.select("script[src]"), "src", "Static JS", requests);
            findApiEndpointsInElements(doc.select("link[href]"), "href", "Static CSS", requests);
            findApiEndpointsInElements(doc.select("img[src]"), "src", "Static Image", requests);
            findApiEndpointsInElements(doc.select("a[href]"), "href", "Static Link", requests);

            // 增强静态分析 - 查找更多可能的API端点
            findApiEndpointsInElements(doc.select("iframe[src]"), "src", "Static Iframe", requests);
            findApiEndpointsInElements(doc.select("source[src]"), "src", "Static Source", requests);
            findApiEndpointsInElements(doc.select("embed[src]"), "src", "Static Embed", requests);
            findApiEndpointsInElements(doc.select("object[data]"), "data", "Static Object", requests);
            findApiEndpointsInElements(doc.select("video[src]"), "src", "Static Video", requests);
            findApiEndpointsInElements(doc.select("audio[src]"), "src", "Static Audio", requests);

            // 分析内联脚本中的URL
            analyzeInlineScripts(doc, requests);

            // 分析数据属性中的URL
            analyzeDataAttributes(doc, requests);

            // 查找页面导航链接
            findNavigationLinks(doc, url, requests);

            logger.info("静态分析完成，共找到 {} 个潜在API端点", requests.size());
        } catch (Exception e) {
            logger.error("静态分析失败: {}", e.getMessage(), e);
        }
        return requests;
    }

    private void findNavigationLinks(Document doc, String baseUrl, List<ApiRequest> requests) {
        // 查找所有导航链接
        Elements links = doc.select("a[href]");
        for (Element link : links) {
            String href = link.attr("href");
            String linkText = link.text().trim();
            String linkTitle = link.attr("title");

            // 解析相对链接
            String absoluteUrl = resolveUrl(baseUrl, href);
            if (absoluteUrl != null) {
                // 检查是否为导航链接（基于链接文本或标题）
                if (isNavigationLink(linkText, linkTitle, absoluteUrl)) {
                    logger.debug("发现导航链接: {} -> {}", linkText, absoluteUrl);
                    ApiRequest navRequest = new ApiRequest("GET", absoluteUrl, "Static Navigation", null, "navigation");
                    navRequest.setTimestamp(System.currentTimeMillis());
                    requests.add(navRequest);
                }
            }
        }
    }

    private boolean isNavigationLink(String linkText, String linkTitle, String url) {
        // 检查链接文本或标题是否表明这是一个导航链接
        String text = (linkText + " " + linkTitle).toLowerCase();
        return text.contains("blog") ||
                text.contains("about") ||
                text.contains("contact") ||
                text.contains("career") ||
                text.contains("work") ||
                text.contains("team") ||
                text.contains("product") ||
                text.contains("feature") ||
                text.contains("doc") ||
                text.contains("help") ||
                text.contains("support") ||
                text.contains("twitter") ||
                text.contains("linkedin") ||
                url.contains("/blog") ||
                url.contains("/about") ||
                url.contains("/contact") ||
                url.contains("/career") ||
                url.contains("/team") ||
                url.contains("/product") ||
                url.contains("/feature") ||
                url.contains("/docs") ||
                url.contains("/help") ||
                url.contains("/support");
    }

    private String resolveUrl(String baseUrl, String href) {
        try {
            java.net.URI baseUri = java.net.URI.create(baseUrl);
            java.net.URI resolvedUri = baseUri.resolve(href);
            return resolvedUri.toString();
        } catch (Exception e) {
            logger.debug("无法解析URL: {} + {} - {}", baseUrl, href, e.getMessage());
            return null;
        }
    }

    private void findApiEndpointsInElements(Elements elements, String attrName, String source, List<ApiRequest> requests) {
        for (Element element : elements) {
            String url = element.attr(attrName);
            if (isValidApiEndpoint(url)) {
                String absoluteUrl = resolveUrl(element.baseUri(), url);
                if (absoluteUrl != null) {
                    ApiRequest request = new ApiRequest("GET", absoluteUrl, source, null, "resource");
                    request.setTimestamp(System.currentTimeMillis());
                    requests.add(request);
                }
            }
        }
    }

    private void analyzeInlineScripts(Document doc, List<ApiRequest> requests) {
        Elements scripts = doc.select("script");
        for (Element script : scripts) {
            String scriptContent = script.data();
            if (scriptContent != null && !scriptContent.isEmpty()) {
                findUrlsInText(scriptContent, "Inline Script", requests);
            }
        }
    }

    private void analyzeDataAttributes(Document doc, List<ApiRequest> requests) {
        Elements elements = doc.select("*[data-*]");
        for (Element element : elements) {
            for (Map.Entry<String, String> attr : element.attributes().asList()) {
                if (attr.getKey().startsWith("data-") && isValidApiEndpoint(attr.getValue())) {
                    String absoluteUrl = resolveUrl(element.baseUri(), attr.getValue());
                    if (absoluteUrl != null) {
                        ApiRequest request = new ApiRequest("GET", absoluteUrl, "Data Attribute", null, "data");
                        request.setTimestamp(System.currentTimeMillis());
                        requests.add(request);
                    }
                }
            }
        }
    }

    private void findUrlsInText(String text, String source, List<ApiRequest> requests) {
        // 简单的URL提取正则表达式
        java.util.regex.Pattern urlPattern = java.util.regex.Pattern.compile(
                "\\b(?:https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]",
                java.util.regex.Pattern.CASE_INSENSITIVE);
        java.util.regex.Matcher matcher = urlPattern.matcher(text);
        while (matcher.find()) {
            String url = matcher.group();
            if (isValidApiEndpoint(url)) {
                ApiRequest request = new ApiRequest("GET", url, source, null, "extracted");
                request.setTimestamp(System.currentTimeMillis());
                requests.add(request);
            }
        }
    }

    private boolean isValidApiEndpoint(String url) {
        if (url == null || url.isEmpty()) {
            return false;
        }
        // 过滤掉无效的URL
        return !url.startsWith("mailto:") &&
                !url.startsWith("tel:") &&
                !url.startsWith("javascript:") &&
                !url.contains("google-analytics.com") &&
                !url.contains("facebook.com/tr") &&
                !url.contains("doubleclick.net") &&
                (url.startsWith("http://") || url.startsWith("https://"));
    }

    private List<ApiRequest> performDynamicAnalysis(String url, String username, String password) {
        logger.info("开始对 {} 进行动态分析", url);
        List<ApiRequest> requests = new CopyOnWriteArrayList<>();
        Playwright playwright = null;
        Browser browser = null;
        BrowserContext context = null;
        Page page = null;

        try {
            // 初始化Playwright
            // 初始化Playwright
            playwright = Playwright.create();

            // 获取浏览器路径配置
            String playwrightBrowsersPath = System.getenv("PLAYWRIGHT_BROWSERS_PATH");
            if (playwrightBrowsersPath == null || playwrightBrowsersPath.isEmpty()) {
                // 使用相对路径作为默认值
                playwrightBrowsersPath = "src/main/resources/playwright-browsers";
            }

            Map<String, String> env = new HashMap<>(System.getenv());
            env.put("PLAYWRIGHT_BROWSERS_PATH", playwrightBrowsersPath);

            // 启动HTTPS代理服务
            try {
                if (!httpsProxyService.isProxyRunning()) {
                    httpsProxyService.startProxy();
                    logger.info("HTTPS代理服务已启动，端口: {}", httpsProxyService.getProxyPort());
                }
            } catch (Exception e) {
                logger.warn("启动HTTPS代理服务失败: {}", e.getMessage());
            }

            BrowserType chromium = playwright.chromium();
            // 配置浏览器使用代理
            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions()
                    .setHeadless(true)
                    .setEnv(env);

            // 正确设置代理
            if (httpsProxyService.isProxyRunning()) {
                launchOptions.setProxy("localhost:" + httpsProxyService.getProxyPort());
            }

            browser = chromium.launch(launchOptions);
            browser = chromium.launch(launchOptions);

            // 创建浏览器上下文
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions();

            // 获取CA证书PEM格式并设置为浏览器信任的证书
            String caCertPem = httpsProxyService.getCACertificatePEM();
            if (caCertPem != null && !caCertPem.isEmpty()) {
                // 尽管Playwright不直接支持添加CA证书，但我们可以通过忽略HTTPS错误来绕过这个问题
                contextOptions.setIgnoreHTTPSErrors(true);
                logger.debug("已配置忽略HTTPS证书错误以支持代理解密");
            }

            context = browser.newContext(contextOptions);

            // 如果提供了登录凭据，则先登录
            if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
                logger.info("尝试使用提供的凭据登录");
                // 这里应该根据目标网站的具体登录机制进行实现
                // 例如，导航到登录页面，填写表单并提交
            }

            // 添加请求拦截和修改功能
            setupRequestInterception(context, requests);

            // 监听网络请求
            Map<String, String> requestIdMap = new HashMap<>(); // 存储request对象到requestId的映射
            String initialPageRequestId = UUID.randomUUID().toString(); // 初始页面请求ID

            context.onRequest(request -> {
                try {
                    String requestUrl = request.url();
                    logger.debug("发送网络请求: {} {}", request.method(), requestUrl);

                    // 创建API请求对象
                    ApiRequest apiRequest = new ApiRequest();
                    apiRequest.setMethod(request.method());
                    apiRequest.setUrl(requestUrl);
                    apiRequest.setSource("Dynamic");
                    apiRequest.setTimestamp(System.currentTimeMillis());

                    boolean intercepted = false;
                    if (interceptChecker != null) {
                        intercepted = interceptChecker.apply(requestUrl);
                    }
                    apiRequest.setIntercepted(intercepted);

                    // 获取请求头
                    Map<String, String> requestHeaders = new HashMap<>();
                    request.headers().forEach((key, value) -> requestHeaders.put(key, value));
                    apiRequest.setRequestHeaders(requestHeaders);

                    // 获取请求体
                    try {
                        String postData = request.postData();
                        if (postData != null && !postData.isEmpty()) {
                            apiRequest.setRequestBody(postData);
                            logger.debug("请求体大小: {} 字节", postData.length());
                        }
                    } catch (Exception e) {
                        logger.debug("无法获取请求体: {}", e.getMessage());
                    }

                    requests.add(apiRequest);

                    if (requestBroadcaster != null) {
                        requestBroadcaster.accept(apiRequest);
                    }

                    // 更新监控数据
                    if (intercepted || shouldModifyRequest(request)) {
                        // 假设MonitorController是可用的，实际应用中可能需要通过其他方式访问
                        // monitorController.incrementRequestCount();
                    }
                } catch (Exception e) {
                    logger.error("处理请求时出错: {}", e.getMessage(), e);
                }
            });

            // 监听网络响应
            context.onResponse(response -> {
                try {
                    String responseUrl = response.url();
                    logger.debug("收到网络响应: {} 状态码: {}", responseUrl, response.status());
                    requests.stream()
                            .filter(req -> req.getUrl().equals(responseUrl))
                            .findFirst()
                            .ifPresent(req -> {
                                try {
                                    req.setStatus(response.status());
                                    req.setType(response.request().resourceType());
                                    logger.debug("收到响应: {} {} 状态码: {}", req.getMethod(), responseUrl, response.status());

                                    // 获取响应头
                                    Map<String, String> responseHeaders = new HashMap<>();
                                    response.headers().forEach((key, value) -> responseHeaders.put(key, value));
                                    req.setResponseHeaders(responseHeaders);

                                    // 获取响应体
                                    try {
                                        response.finished();
                                        String responseBody = response.text();
                                        if (responseBody != null && !responseBody.isEmpty()) {
                                            req.setResponseBody(responseBody);
                                            logger.debug("响应体大小: {} 字节", responseBody.length());
                                        }
                                    } catch (Exception e) {
                                        logger.debug("无法获取响应体: {}", e.getMessage());
                                    }

                                    // 获取响应时间
                                    try {
                                        req.setResponseTime((long) response.request().timing().responseEnd);
                                    } catch (Exception e) {
                                        logger.debug("无法获取响应时间: {}", e.getMessage());
                                    }
                                } catch (Exception e) {
                                    logger.error("处理响应时出错: {}", e.getMessage(), e);
                                }
                            });
                } catch (Exception e) {
                    logger.error("处理响应时出错: {}", e.getMessage(), e);
                }
            });

            // 访问多个页面（包括导航链接）
            Queue<String> urlsToVisit = new LinkedList<>();
            Set<String> visitedUrls = new HashSet<>(); // 用于跟踪已访问的URL，避免重复访问
            urlsToVisit.offer(url); // 将初始URL添加到待访问队列中

            int maxPages = 5; // 限制访问的页面数量
            int visitedCount = 0;

            while (!urlsToVisit.isEmpty() && visitedCount < maxPages) {
                String currentUrl = urlsToVisit.poll();
                if (currentUrl == null || visitedUrls.contains(currentUrl)) {
                    continue;
                }

                visitedUrls.add(currentUrl);
                visitedCount++;
                logger.debug("导航到页面: {} ({}/{})", currentUrl, visitedCount, maxPages);
                page = context.newPage();

                // 访问页面
                page.navigate(currentUrl);

                // 等待页面加载完成
                page.waitForLoadState(LoadState.NETWORKIDLE);
                Thread.sleep(2000); // 额外等待2秒确保所有请求完成

                // 在动态分析中查找更多导航链接
                try {
                    // 提取页面中的所有链接
                    Object links = page.evaluate("() => Array.from(document.querySelectorAll('a[href]')).map(a => a.href)");
                    if (links instanceof List) {
                        List<?> linkList = (List<?>) links;
                        logger.debug("从页面 {} 提取到 {} 个链接", currentUrl, linkList.size());

                        // 将有效的、未访问过的链接添加到待访问队列
                        for (Object linkObj : linkList) {
                            if (linkObj instanceof String) {
                                String link = (String) linkObj;
                                if (isValidApiEndpoint(link) && !visitedUrls.contains(link)) {
                                    urlsToVisit.offer(link);
                                    logger.debug("添加链接到待访问队列: {}", link);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.warn("提取页面链接时出错: {}", e.getMessage());
                }

                // 关闭当前页面
                page.close();
                page = null;
            }

            logger.debug("页面加载完成");

        } catch (Exception e) {
            logger.error("动态分析失败: {}", e.getMessage(), e);
        } finally {
            // 安全关闭所有资源，按正确的顺序关闭
            // 注意：Playwright对象会自动清理其创建的子对象，所以我们只需要显式关闭Playwright
            if (playwright != null) {
                try {
                    playwright.close();
                    logger.debug("Playwright已关闭");
                } catch (Exception e) {
                    logger.error("关闭Playwright时出错: {}", e.getMessage(), e);
                }
            }
        }

        logger.info("动态分析完成，共捕获 {} 个网络请求", requests.size());
        return requests;
    }

    /**
     * 设置请求拦截和修改功能
     */
    private void setupRequestInterception(BrowserContext context, List<ApiRequest> requests) {
        // 拦截所有请求
        context.route("**/*", route -> {
            // 获取原始请求
            Request request = route.request();
            String requestUrl = request.url();

            // 检查是否需要拦截
            boolean shouldIntercept = false;
            if (interceptChecker != null) {
                shouldIntercept = interceptChecker.apply(requestUrl);
            }

            // 使用shouldModifyRequest方法判断是否需要修改请求
            boolean shouldModify = shouldModifyRequest(request);

            if (shouldIntercept || shouldModify) {
                logger.info("拦截请求: {} {}", request.method(), requestUrl);

                // 获取原始请求头
                Map<String, String> headers = new HashMap<>(request.headers());

                // 应用修改规则（示例：添加自定义头）
                headers.put("X-Intercepted-By", "WebCrawler");

                // 创建修改后的请求对象
                ApiRequest modifiedRequest = new ApiRequest();
                modifiedRequest.setMethod(request.method());
                modifiedRequest.setUrl(requestUrl);
                modifiedRequest.setSource("Dynamic");
                modifiedRequest.setIntercepted(shouldIntercept);
                modifiedRequest.setModified(shouldModify);
                modifiedRequest.setTimestamp(System.currentTimeMillis());
                modifiedRequest.setRequestHeaders(headers);

                // 获取请求体
                try {
                    String postData = request.postData();
                    if (postData != null && !postData.isEmpty()) {
                        modifiedRequest.setRequestBody(postData);
                    }
                } catch (Exception e) {
                    logger.debug("无法获取请求体: {}", e.getMessage());
                }

                // 添加到请求列表
                requests.add(modifiedRequest);

                // 继续请求但使用修改后的参数
                route.resume(new Route.ResumeOptions()
                        .setMethod(request.method())
                        .setHeaders(headers)
                        .setPostData(request.postData()));
            } else {
                // 正常继续请求
                route.resume();
            }
        });
    }

    /**
     * 判断是否需要修改请求
     */
    private boolean shouldModifyRequest(Request request) {
        // 示例逻辑：修改包含特定关键词的请求
        return request.url().contains("/api/") &&
                ("POST".equals(request.method()) || "PUT".equals(request.method()));
    }

    public String getPlaywrightInfo() {
        try {
            // 检查系统环境变量
            String browsersPath = System.getenv("PLAYWRIGHT_BROWSERS_PATH");
            if (browsersPath == null || browsersPath.isEmpty()) {
                browsersPath = "未设置 (将使用默认路径)";
            }

            // 检查浏览器目录
            File browsersDir = new File("D:\\IDEAProjet\\API\\src\\main\\resources\\playwright-browsers");
            boolean browsersExist = browsersDir.exists() && browsersDir.isDirectory();

            StringBuilder info = new StringBuilder();
            info.append("PLAYWRIGHT_BROWSERS_PATH: ").append(browsersPath).append("\n");
            info.append("浏览器目录存在: ").append(browsersExist ? "是" : "否").append("\n");

            if (browsersExist) {
                File[] browserDirs = browsersDir.listFiles(File::isDirectory);
                if (browserDirs != null) {
                    info.append("已安装的浏览器:\n");
                    for (File dir : browserDirs) {
                        info.append("  - ").append(dir.getName()).append("\n");
                    }
                }
            }

            return info.toString();
        } catch (Exception e) {
            return "获取Playwright信息时出错: " + e.getMessage();
        }
    }

    private boolean checkPlaywrightInstallation(WebAnalysisService service) {
        try {
            // 尝试创建Playwright实例来验证安装
            try (com.microsoft.playwright.Playwright playwright = com.microsoft.playwright.Playwright.create()) {
                // 尝试启动浏览器来验证安装
                com.microsoft.playwright.Browser browser = playwright.chromium()
                        .launch(new com.microsoft.playwright.BrowserType.LaunchOptions().setHeadless(true));
                browser.close();
                return true;
            }
        } catch (Exception e) {
            System.err.println("Playwright安装检查失败: " + e.getMessage());
            return false;
        }
    }

}
